<?php
declare (strict_types=1);

namespace app\admin\model\media;

use app\admin\model\BaseModel;

class Article extends BaseModel
{
    //当前模型对应的数据表名称
    protected $name = 'media_article';

    public function getList($filter = []): array
    {
        $where = function ($query) use ($filter) {
            if (isset($filter['group_id'])) {
                $query->where('module_id', 'in', function ($query) use ($filter) {
                    $query->name("media_module")->where("group_id", '=', $filter['group_id'])->field('module_id');
                });
            }
            if (isset($filter['website_id'])) {
                $query->where('module_id', 'in', function ($query) use ($filter) {
                    $query->name("media_module")->where("website_id", '=', $filter['website_id'])->field('module_id');
                });
            }
            if (isset($filter['module_id'])) {
                $query->where('module_id', '=', $filter['module_id']);
            }
            if (isset($filter['title'])) {
                $query->where('title', 'like', '%' . $filter['title'] . '%');
            }
            if (isset($filter['url'])) {
                $query->where('url', 'like', '%' . $filter['url'] . '%');
            }
            if (isset($filter['time'])) {
                $startTime = date('Y-m-d', strtotime($filter['time'][0])) . ' 00:00:00';
                $endTime = date('Y-m-d', strtotime($filter['time'][1])) . ' 23:59:59';
                $query->whereTime('time', 'between', [$startTime, $endTime]);
            }
        };
        $order = ['time' => 'desc', 'createtime' => 'desc', 'id' => 'asc'];
        return self::getPageList($where, $order);
    }

    public function getPageList($where = [], $order = [], $page = 0, $limit = 0)
    {
        $page = $page ?: request()->param("page", 1, 'intval');
        $limit = $limit ?: request()->param("limit", 10, 'intval');

        $total = self::
        where($where)
            ->count();

        $list = self::with(['module'])
            ->where($where)
            ->order($order)
            ->page($page, $limit)
            ->select();

        return [$total, $list];
    }


    public function saveArticleList($list, $module)
    {
        $dataList = [];
        $codeList = [];

        $WebsiteModel = new Website();

        $config = json_decode($module['rules'], true);

        foreach ($list as $key => $item) {
            $arrData = $item;
            $arrData['module_id'] = $module['id'];
            if (empty($item['time'])) {
                $arrData['time'] = time();
            } else {
                $time = is_numeric($item['time']) ? $item['time'] : strtotime($item['time']);
                $arrData['time'] = $time;
            }
            if (!empty($config['rules']['full_url'])) {
                $replaceArr = [
                    '{title}' => $arrData['title'],
                    '{cover}' => $arrData['cover'],
                    '{url}' => $arrData['url'],
                    '{time}' => $arrData['time'],
                    '{extra}' => $arrData['extra'],
                ];
                $arrData['url'] = str_replace(array_keys($replaceArr), array_values($replaceArr), $config['rules']['full_url']);
            }

            $arrData['code'] = md5($arrData['title'] . $arrData['time']);
            $codeList[] = $arrData['code'];

            $dataList[] = $arrData;
        }
        if ($dataList) {
            $oldArticle = $this
                ->where('module_id', '=', $module['id'])
                ->where('code', 'in', $codeList)
                ->column('code');
            foreach ($dataList as $key => $item) {
                if (in_array($item['code'], $oldArticle)) {
                    unset($dataList[$key]);
                }
            }
            if ($dataList) {
                $this->saveAll($dataList);

                //模块文章数量
                $moduleArticleCount = $this->where('module_id', '=', $module['id'])->count('id');
                $module->save(['article_num' => $moduleArticleCount]);

                //网站文章数量
                $websiteArticleCount = $this->where('module_id', 'in', function ($query) use ($module) {
                    $query->name("media_module")->where("website_id", '=', $module['website_id'])->field('module_id');
                })
                    ->count('id');

                $website = $WebsiteModel->where('id', '=', $module['website_id'])->find();
                $website->save(['article_num' => $websiteArticleCount]);

            }
        }
    }

    public function getTimeAttr($value, $data)
    {
        if ($value) {
            return date('Y-m-d', $value);
        } else {
            return '';
        }
    }

    public function module()
    {
        return $this->belongsTo('Module', 'module_id', 'id')
            ->with(['group', 'website'])
            ->field('id,group_id,website_id,name');
    }

}